<template>
  <div>
    <el-form :model="spuForm" label-width="100px">
      <el-form-item label="SPU名称">
        <el-input
          v-model="spuForm.spuName"
          placeholder="请输入SPU名称"
        ></el-input>
      </el-form-item>

      <el-form-item label="品牌">
        <el-select v-model="spuForm.tmId" placeholder="请选择品牌">
           <el-option 
            v-for="marketAttr in marketAttrList"
            :label="marketAttr.tmName"
            :value="marketAttr.id"
            :key="marketAttr.id">
          </el-option>

        </el-select>
      </el-form-item>

      <el-form-item label="SPU描述">
        <el-input
          type="textarea"
          v-model="spuForm.description"
          placeholder="请输入SPU描述"
          :rows="4"
        ></el-input>
      </el-form-item>

      <el-form-item label="SPU图片">

        <el-upload
          action="/dev-api/admin/product/fileUpload"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-success="handleSuccess" 
          :file-list="spuImgList"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>

      </el-form-item>

      <el-form-item label="销售属性">
        <el-select v-model="baseSaleAttrIdName" :placeholder="unUsedSpuSaleAttrList.length > 0 ? `还有${unUsedSpuSaleAttrList.length}个未选`:'啥都没了'">
          <el-option :label="unUsedSpuSaleAttr.name" :value="`${unUsedSpuSaleAttr.id}:${unUsedSpuSaleAttr.name}`" v-for="unUsedSpuSaleAttr in unUsedSpuSaleAttrList" :key="unUsedSpuSaleAttr.id"></el-option>
        </el-select>
        <el-button
          type="primary"
          icon="el-icon-plus"
          :disabled="!baseSaleAttrIdName"
          @click="addSaleAttr">
          添加销售属性
        </el-button>

        <template>
          <el-table border style="width: 100%; margin: 10px 0" :data="spuForm.spuSaleAttrList">
            <el-table-column
              type="index"
              width="80"
              label="序号"
              align="center"
            ></el-table-column>
            <el-table-column label="属性名" width="150" prop="saleAttrName"></el-table-column>
            <el-table-column label="属性值名称列表" width="width">
              <template slot-scope="{ row, $index }">
                <el-tag
                  :key="spuSaleAttrValue.id"
                  v-for="(spuSaleAttrValue,index) in row.spuSaleAttrValueList"
                  closable
                  :disable-transitions="false"
                  @close="row.spuSaleAttrValueList.splice(index,1)">
                  {{spuSaleAttrValue.saleAttrValueName}}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="row.inputVisible"
                  v-model="row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="$event.target.blur"
                  @blur="handleInputConfirm(row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(row)">+ 添加</el-button>
              </template>
            </el-table-column>

            <el-table-column label="操作" width="150">
              <template slot-scope="{ row, $index }">
                  <el-popconfirm
                    confirm-button-text='确定'
                    cancel-button-text='取消'
                    icon="el-icon-info"
                    icon-color="red"
                    :title="`确定删除:${row.saleAttrName}吗？`"
                    @onConfirm="delSaleAttrName(row,$index)"
                  >
                    <el-button slot="reference" icon="el-icon-delete" type="danger"></el-button>
                  </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </template>

        <el-button type="primary" @click="save">保存</el-button>
        <el-button @click="close">取消</el-button>

      </el-form-item>
    </el-form>
  </div>
</template>


<script>
export default {
  name: "spuForm",
  data() {
    return {
      spuForm: {
        category3Id: 0,
        description: "",
        tmId: '',
        spuName: "",
        spuImageList: [],
        spuSaleAttrList: [],
      },

      marketAttrList: [], //存放所有的销属性

      spuImgList:[],    // 存放修改的按钮请求回来的数据

      baseSaleAttrIdName : '', //存放销售属性的ID

      saleAttrResult:[], //存放所有的销售属性


      dialogImageUrl: '',
      dialogVisible: false,

      isAddOrUpdate:'',     //判断是添加还是修改的标志位
      
      inputVisible:false,
    };
  },
  computed: {
    //用来展示未选的销售属性
    unUsedSpuSaleAttrList(){
      return this.saleAttrResult.filter((saleAttr)=>{
          return this.spuForm.spuSaleAttrList.every((spuSaleAttr)=>{
            return spuSaleAttr.saleAttrName !== saleAttr.name
          })
      })
    },
  },
  methods: {
     close(){
       this.resetInitDate() //清空数据
       this.$emit('update:visible',false)
     },
     handlePictureCardPreview(file) {
       this.dialogImageUrl = file.url;
       this.dialogVisible = true;
     },
     //删除图片成功的回调
     handleRemove(file, fileList){
       //file表示删除的项，fileList表示删除后数组的数据
       this.spuImgList = fileList;
     },
     //添加图片成功的回调
     handleSuccess(response, file, fileList){
       let obj = {...file};
       obj.imgName = obj.name;
       obj.imgUrl = response.data
       obj.url = response.data
       this.spuImgList.push(obj);
     },
     //点击修改SPU请求获取初始化数据
    async initUpdataSpuFormData(spu){
    //获取spu的详情
    //http://localhost:9529/dev-api/admin/product/getspubyid/4
    //获取spu的图片列表数据
    //http://localhost:9529/dev-api/admin/product/spuimagelist/4
    //获取所有的品牌列表数据
    //http://localhost:9529/dev-api/admin/product/basetrademark/gettrademarklist
    //获取所有的销售属性数据
    //http://localhost:9529/dev-api/admin/product/basesaleattrlist
        const result = await this.$API.spu.get(spu.id);  //获取spu的详情
            if(result.code == 200){
              this.spuForm = result.data
            }

        const imgresult = await this.$API.sku.getSpuImageList(spu.id);    //获取spu的图片列表数据
            if(imgresult.code === 200){
                let imgeList = imgresult.data;
                imgeList.forEach(item => {
                  item.name = item.imgName
                  item.url = item.imgUrl
                });
                this.spuImgList = imgeList
            }

        const trademarkResult =await this.$API.trademark.getTrademarkList();  //获取所有的品牌数据
            if(trademarkResult.code === 200) {
              this.marketAttrList = trademarkResult.data
            }

        const saleAttrResult =await this.$API.spu.getSaleAttrList();    //获取所有的销售属性数据
            if(saleAttrResult.code === 200){
              this.saleAttrResult = saleAttrResult.data;
            }
    
    },
    //点击添加销售属性的标签
    showInput(row){
      this.$set(row,'inputVisible',true)    
      //row.inputVisible = true;
      this.$nextTick(()=>{
        this.$refs.saveTagInput.focus();    //自动获取焦点
      })
    },
    //添加属性值名称的操作
    handleInputConfirm(row){
      let saleAttrValueName = row.inputValue;
      if(saleAttrValueName.trim() === ''){
        this.$message.info("请输入属性值名称");
        return
      }
      let isChecked = row.spuSaleAttrValueList.some((item)=>{
        return item.saleAttrValueName === row.inputValue;
      })
      if(isChecked){
        this.$message.error('属性值已存在');
        row.inputValue = '';
        return;
      }
      row.spuSaleAttrValueList.push({
         saleAttrValueName,
         baseSaleAttrId:row.baseSaleAttrId,  //此属性为后续特定提交格式
      })
      row.inputVisible = false;
      row.inputValue = '';
    },
    //点击点击销售属性
    addSaleAttr(){
      let [baseSaleAttrId,saleAttrName] = this.baseSaleAttrIdName.split(":");
      // console.log(baseSaleAttrId,saleAttrName)
      this.spuForm.spuSaleAttrList.push({
          baseSaleAttrId,
          saleAttrName,
          spuSaleAttrValueList: [],
      })
      this.baseSaleAttrIdName = '';
    },
    delSaleAttrName(index){
      this.spuForm.spuSaleAttrList.splice(index,1);
    },
    //点击添加spu请求相关数据
    async initAddSpuFromData(category3Id){
      this.spuForm.category3Id = category3Id;
      this.isAddOrUpdate = true;    //设置标志位，代表当前操作为添加
      //获取所有的品牌列表数据
      //http://localhost:9529/dev-api/admin/product/basetrademark/gettrademarklist
      //获取所有的销售属性数据
      //http://localhost:9529/dev-api/admin/product/basesaleattrlist
      const trademarkResult =await this.$API.trademark.getTrademarkList();  //获取所有的品牌数据
            if(trademarkResult.code === 200) {
              this.marketAttrList = trademarkResult.data
            }
      const saleAttrResult =await this.$API.spu.getSaleAttrList();    //获取所有的销售属性数据
            if(saleAttrResult.code === 200){
              this.saleAttrResult = saleAttrResult.data;
            }
    },
    //点击保存的回调
    async save(){
      this.spuForm.spuImageList = this.spuImgList;    //把收集到的图片赋给提交数据
      if(this.isAddOrUpdate){
         await this.$API.spu.addUpdate(this.spuForm);
         this.$message.success("添加SPU成功");
         this.resetInitDate() //清空数据
         this.$emit('update:visible',false);
         this.$emit("saveSpu")
      }else{
          try {
            await this.$API.spu.addUpdate(this.spuForm);
            this.$message.success("SPU修改成功");
            this.resetInitDate() //清空数据
            this.$emit('update:visible',false);
            //通知父组件重新获取请求
            this.$emit("saveSpu",1);
          } catch (error) {
            this.$message.error(error.message);
          }
      }
      
      
    },
    //初始化data中的数据
    resetInitDate(){
       this.spuForm = {
          category3Id: 0,
          description: "",
          tmId: '',
          spuName: "",
          spuImageList: [],
          spuSaleAttrList: [],
       },
       this.spuImgList = [];
       this.isAddOrUpdate = '';
    },

   }
};
</script>

<style>
  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
</style>
